<template>
  <el-dropdown class="import-button" @command="handleImportCommand" :disabled="isWorking">
    <el-button>
      {{ isWorking ? '数据导入中...' : text }}<i class="el-icon-arrow-down el-icon--right"></i>
    </el-button>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="download">下载模版</el-dropdown-item>
      <el-dropdown-item command="import">
        <el-upload
          ref="uploader"
          :action="action"
          :show-file-list="false"
          accept=".xlsx"
          :on-progress="handleImporting"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
        >
          <span>{{ isWorking ? '数据导入中...' : '开始导入' }}</span>
        </el-upload>
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { downloadLocalFile } from '@/api/system/common'
export default {
  name: 'ImportButton',
  props: {
    // 按钮文案
    text: {
      default: '导入'
    },
    // 模版地址
    templatePath: {
      required: true
    },
    // 下载后的模版文件名称
    templateName: {
      required: true
    },
    // 导入接口地址
    action: {
      required: true
    }
  },
  data () {
    return {
      isWorking: false
    }
  },
  methods: {
    // 处理导入命令
    handleImportCommand (command) {
      // 下载
      if (command === 'download') {
        downloadLocalFile({
          path: this.templatePath,
          name: this.templateName
        })
          .then(data => {
            this.download(data)
          })
          .catch(e => {
            this.$tip.apiFailed(e)
          })
      }
      if (command === 'import') {
        this.$refs.uploader.submit()
      }
    },
    // 处理导入中状态
    handleImporting () {
      this.isWorking = true
    },
    // 处理导入成功
    handleImportSuccess (response) {
      this.isWorking = false
      if (response.code !== 200) {
        this.$tip.apiFailed(response)
        return
      }
      this.$tip.success('导入成功，共导入' + response.data + '条记录')
      this.$emit('success', response.data)
    },
    // 处理导入失败
    handleImportError (err) {
      this.isWorking = false
      this.$tip.apiFailed(err)
    }
  }
}
</script>

<style scoped lang="scss">
.import-button {
  .el-upload {
    span {
      display: block;
    }
  }
}
</style>
